package com.cloudbroker.bcs.common.jres.service;

import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

import com.hundsun.jresplus.remoting.impl.annotation.Service;

public abstract class FunctionIdAccessServiceAdapterBase<T> {
    
    protected Map<String, Method> methodMap = new HashMap<String, Method>();
    
    protected FunctionIdAccessServiceAdapterBase() {
        initMethodMap();
    }
    
    protected void initMethodMap() {
        Class<?> apiServiceClass = getTargetServiceClass();
        Method[] methods = apiServiceClass.getMethods();
        for (Method method : methods) {
            Service serviceAnn = method.getAnnotation(Service.class);
            if (null != serviceAnn) {
                String functionId = serviceAnn.functionId();
                methodMap.put(functionId, method);
            }
        }
    }
    
    @SuppressWarnings("unchecked")
    protected Class<T> getTargetServiceClass() {
        // 根据泛型获得APIService接口类型
        Type type = super.getClass().getGenericSuperclass();
        if (type instanceof ParameterizedType) {
            return (Class<T>) ((ParameterizedType) type).getActualTypeArguments()[0];
        } else {
            throw new RuntimeException("error type of adapter");
        }
    }
    
    protected abstract T getTargetService();
    
    protected Method getMethod(String functionId) {
        Method method = methodMap.get(functionId);
        if (null == method) {
            throw new IllegalArgumentException("unknown method(functionId): " + functionId);
        }
        return method;
    }
    
}
